﻿using System.Text.Json;
using System.Text.Json.Serialization;


namespace System.Text.Json;

/// <summary>
/// Double类型序列化保留2位小数
/// </summary>
public class DoubleConverter : JsonConverter<double>
{
    public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = reader.GetDouble();
        return Math.Round(value, 2);
    }

    public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options)
    {
        var roundedValue = Math.Round(value, 2);
        writer.WriteNumberValue(roundedValue);
    }
}

/// <summary>
/// Float类型序列化保留2位小数
/// </summary>
public class FloatConverter : JsonConverter<float>
{
    public override float Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = reader.GetDecimal();
        return (float)Math.Round(value, 2);
    }

    public override void Write(Utf8JsonWriter writer, float value, JsonSerializerOptions options)
    {
        var roundedValue = Math.Round(value, 2);
        writer.WriteNumberValue(roundedValue);
    }
}


////测试
//using System.Text.Json;
//using System.Text.Json.Serialization;
//namespace Test
//{
//    public class Model
//    {
//        /// <summary>
//        /// Float字段
//        /// </summary>
//        [JsonPropertyName("float_field")]
//        [JsonConverter(typeof(FloatConverter))]
//        public float FloatField { get; set; }


//        /// <summary>
//        /// Double字段
//        /// </summary>
//        [JsonPropertyName("double_field")]
//        [JsonConverter(typeof(DoubleConverter))]
//        public double DoubleField { get; set; }

//        public override string ToString()
//        {
//            return JsonSerializer.Serialize(this);
//        }
//    }

//    class Program
//    {
//        static void Main(string[] args)
//        {
//            var myObject = new Model { FloatField = 2.71828F, DoubleField = 3.1415926 };
//            string json = JsonSerializer.Serialize(myObject);
//            Console.WriteLine($"序 列 化： {json}");

//            var obj = JsonSerializer.Deserialize<Model>(json);
//            Console.WriteLine($"反序列化：{obj} ");
//            Console.ReadLine();
//        }
//    }
//}